package com.ai.chatai.controller;

import com.ai.chatai.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.content.Media;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;
import org.springframework.util.MimeType;
import java.util.List;
import java.util.Objects;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {
    private final ChatClient chatClient;
    private final ChatHistoryRepository chatHistoryRepository;
    //返回一个字符串，阻塞式回答
    @RequestMapping("/chat/v1")
    public String chat(String prompt) {
        return chatClient.prompt()
                .user(prompt)
                .call()
                .content();
    }

    //流式回答
    @RequestMapping(value = "/chat",produces = "text/html;charset=utf-8")
    public Flux<String> chatV1(@RequestParam("prompt") String prompt,
                               @RequestParam("chatId") String chatId,
                               @RequestParam(value = "files", required = false) List<MultipartFile> files){
        //1.保存会话id
        chatHistoryRepository.save("chat",chatId);
        //2.请求模型
        if(files== null || files.isEmpty()){
           return textChat(prompt,chatId);
        }else {
            return multiModelChat(prompt,chatId,files);
        }
    }
    private Flux<String> multiModelChat(String prompt, String chatId, List<MultipartFile> files) {
    // 1.解析多媒体文件
        List<Media> medias = files.stream()
                .map(file -> new Media(
                                MimeType.valueOf(Objects.requireNonNull(file.getContentType())),
                                file.getResource()
                        )
                )
                .toList();
        // 2.请求模型
        return chatClient.prompt()
                .user(p -> p.text(prompt).media(medias.toArray(Media[]::new)))// 设置用户输入
                .advisors(a->a.param(ChatMemory.CONVERSATION_ID,chatId))// 设置会话ID
                .stream()// 开启流式对话
                .content();// 获取对话内容
    }

    private Flux<String> textChat(String prompt, String chatId) {
        return chatClient.prompt()
                .user(prompt)// 设置用户输入
                .advisors(a->a.param(ChatMemory.CONVERSATION_ID,chatId))// 设置会话ID
                .stream()// 开启流式对话
                .content();// 获取对话内容
    }
}
